package br.com.news.database.daos;

import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.news.database.daos.interfaces.IEnqueteDao;
import br.com.news.database.entities.EnqueteEntity;
import br.com.news.database.exception.DataBaseException;
import br.com.news.database.utils.GenericDao;

@Named
public class EnqueteDao extends GenericDao<EnqueteEntity, Long> implements IEnqueteDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<EnqueteEntity> getLastPoll() throws DataBaseException {
		try {
			Criteria criteria = getSession()
					.createCriteria(EnqueteEntity.class);
			criteria.add(Restrictions.eq("status", true));
			criteria.addOrder(Order.desc("idEnquete"));
			return criteria.list();
		} catch (Exception e) {
			throw new DataBaseException("Falha ao buscar últimas enquetes!", e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EnqueteEntity> findByQuestion(EnqueteEntity questao) {
		Criteria criteria = getSession().createCriteria(EnqueteEntity.class);
				
		if (questao.getQuestao() != null && !questao.getQuestao().equals("")) {
			criteria.add(Restrictions.like("questao", questao.getQuestao(), MatchMode.ANYWHERE));
		}
		criteria.add(Restrictions.eq("status", questao.isStatus()));
		
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EnqueteEntity> findPollByStatus(boolean status) throws DataBaseException {
		try {
			Criteria criteria = getSession().createCriteria(EnqueteEntity.class);
			criteria.add(Restrictions.eq("status", status));
			return criteria.list();
		} catch (Exception e) {
			throw new DataBaseException("Falha ao procurar enquetes ativas!", e);
		}
	}

}
